import { Base64 } from "js-base64";
import { getCookie } from "@/utils/tool";
import { domain } from "@/config";
import axios from 'axios'


export function computeUrl (tenantId, bizId, relativePaths) {
    return `${domain}serv-file/api/2/file/preview/${
        tenantId
      }/dataset/${
        bizId
      }/${
        encodeURIComponent(Base64.encode(relativePaths))
      }`
  }
export function dataURLtoFile(dataurl, filename) {
    //将base64转换为文件
    var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

export async function getJsonFile(__this, bizId, fileName, fn) {
    let info = await __this.$myInfo(__this);
    let uid = info.orgId;
    axios({
        headers: {
            'Authorization': decodeURIComponent(getCookie('login_ticket'))
        },
        data: {
            bizId,
            relativePath: `/editable/.annotation/${fileName}`,
            tenantId: uid,
            type: 'dataset'
        },
        method: 'post',
        url: `${domain}serv-file/api/2/file/preview`,
    }).then(e => {
        if (typeof (e.data) == 'object' || typeof (e.data) == 'string') {
            fn(e.data)
        } else {
            console.log('没有标注')
        }
    }).catch(e => {
        console.log(e)
    })
}
export async function writeFile(__this, bizId, template, fileName, fn) {

    let info = await __this.$myInfo(__this);
    let uid = info.orgId;
    let filesFile = dataURLtoFile(
        `data:text/json;base64,${Base64.encode(JSON.stringify(template))}`,
        fileName
    );
    let data = new FormData();
    data.append("chunkNumber", 1);
    data.append("totalChunks", 1);
    data.append("repeType", '');
    data.append("filename", fileName);
    data.append("relativePath", `/editable/.annotation/${fileName}`);
    data.append("tenantId", uid);
    data.append("type", 'dataset');
    data.append("uuid", bizId);
    data.append("file", new Blob([filesFile]), fileName);
    axios({
        headers: {
            Authorization: decodeURIComponent(getCookie("login_ticket")),
            "Content-Type": "multipart/form-data",
        },
        data,
        method: "post",
        url: `${domain}serv-file/api/2/file/upload`,
    }).then(async e => {
        if (e.data.code && e.data.code == 401) {
            __this.$router.push({
                path: "/login",
            });
            return;
        }
        if (fn) {
            fn()
        }
    })
}